import time
from utils.name_generator import generator
from task import Task
import threading
import schedule

class Controller(schedule.Scheduler):

    def __init__(self,name=None, tasks=[]):
        schedule.Scheduler.__init__(self)
        if name is None:
            self.name = generator()
        else:
            self.name = name
        self.tasks = tasks
        threading.Thread(target=self.__check_status).start()

    def addTask(self, task_name=None, jobs=None):
        name = task_name
        if name is None:
            name =  generator(prefix=self.name)
        else:
            name = self.name + '-' + name

        task = Task(name=name, controller_name=self.name)
        if jobs is not None:
            task.jobs = jobs

        self.tasks.append(task)
        return task

    def __check_status(self):
        while True:
            self.run_pending()
            time.sleep(1)


    def __str__(self):
        return 'Controller - ' + self.name

    def __repr__(self):
        return 'Controller - ' + self.name

